package com.qdu.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.qdu.entity.Course;
import com.qdu.mapper.CourseMapper;
import com.qdu.service.CourseService;
@Service
public class CourseServiceImpl implements CourseService{
	
	@Autowired
	CourseMapper courseMapper;

	@Override
	public Course selectCourseById(String id) {
		return courseMapper.selectCourseById(id);
	}

	@Override
	public boolean addCourse(Course Course, int acdmid) {
		return courseMapper.addCourse(Course, acdmid);
	}

	@Override
	public boolean modifyCourse(Course Course, int acdmid) {
		return courseMapper.modifyCourse(Course, acdmid);
	}

	@Override
	public boolean deleteCourseById(String id) {
		return courseMapper.deleteCourseById(id);
	}

	@Override
	public List<Course> selectAllCourse() {
		return courseMapper.selectAllCourse();
	}

	@Override
	public List<Course> selectCourseByacdmid(int acdmid) {
		return courseMapper.selectCourseByacdmid(acdmid);
	}

	@Override
	public boolean uploadCourse(MultipartFile file) throws Exception {

		Workbook workbook = WorkbookFactory.create(file.getInputStream());

		Sheet sheet = workbook.getSheet("sheet1");

		int num = sheet.getLastRowNum();

		
		for (int i = 1; i <= num; i++) {
			Row row = sheet.getRow(i);
			Cell cell1 = row.getCell(0);
			Cell cell2 = row.getCell(1);
			Cell cell3 = row.getCell(2);
			Cell cell4 = row.getCell(3);
			Cell cell5 = row.getCell(4);
			Cell cell6 = row.getCell(5);
			Cell cell7 = row.getCell(6);
			if(cell7 == null) {
				cell7 = row.createCell(6);
				cell7.setCellType(CellType.STRING);
			}
			Cell cell8 = row.getCell(7);
			if(cell8 == null) {
				cell8 = row.createCell(6);
				cell8.setCellType(CellType.STRING);
			}
			
			Course course = new Course();
			course.setCname(cell1.getStringCellValue());
			course.setCtype(cell3.getStringCellValue());
			course.setCredit(new BigDecimal(cell4.getNumericCellValue()));
			course.setCmethod(cell5.getStringCellValue());
			course.setCtime((int) cell6.getNumericCellValue());
			if (cell7.getStringCellValue().equals("")) {

			} else {
				course.setCtimeDetail(cell7.getStringCellValue());
			}
			if (cell8.getStringCellValue().equals("")) {

			} else {
				course.setDescription(cell8.getStringCellValue());
			}
			courseMapper.addCourse(course, (int) cell2.getNumericCellValue());
		}

		return true;
	}

	@Override
	public List<Course> selectCourseByKeyword(String keyword) {
		return courseMapper.selectCourseByKeyword(keyword);
	}

}
